package bb.lanxing.util;

import static bb.lanxing.common.config.Constants.LUSHU_BAIDU_FILE_SUFFIX;
import static bb.lanxing.common.config.Constants.LUSHU_GPX_FILE_SUFFIX;
import static bb.lanxing.model.database.RouteBook.TYPE_BAIDU;
import static bb.lanxing.model.database.RouteBook.TYPE_GOOGLE;
import static bb.lanxing.model.database.RouteBook.TYPE_IMPORT;
import static bb.lanxing.model.database.RouteBook.TYPE_SOURCE_CREATE;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.umeng.socialize.net.utils.SocializeProtocolConstants;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.deeplink.DeepLinkPathConstants;
import bb.lanxing.activity.routebook.BaiduRouteBookCreateActivity;
import bb.lanxing.common.config.Constants;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.RouteBookPoint;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Waypoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.json.BiciLatlng;
import bb.lanxing.model.json.Route;
import bb.lanxing.nav.BaiduNavConvert;
import bb.lanxing.nav.PolyAnalyzer;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.io.GpxTrackWriter;
import bb.lanxing.util.io.SaxGpxImporter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RouteBookUtil {
    final private static String TAG = "LushuUtil";
    private static final String KEY_COLLECTION_LUSHU_FIRST = "key_collection_lushu_first";
    private static final String KEY_CREATE_LUSHU_FIRST = "key_create_lushu_first";
    private static final String KEY_DOWNLOAD_LUSHU_FIRST = "key_download_lushu_first";
    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static long exportWorkoutToRouteBook(Context context, long workoutId, boolean isMyRouteBook) {
        if (!AppFileUtils.isSdCardAvailable()) {
            App.getContext().showMessage(R.string.sdcard_null);
            return 0L;
        }
        Workout byId = Workout.getById(workoutId);
        if (byId == null) {
            App.getContext().showMessage("导出失败");
            return 0L;
        }
        List<Trackpoint> queryTrackPoint = WorkoutDatabaseHelper.queryTrackPoint(workoutId);
        if (queryTrackPoint == null || queryTrackPoint.isEmpty()) {
            App.getContext().showMessage("导出失败");
            return 0L;
        }
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_EXPORT);
        if (buildExternalDirectoryPath == null) {
            App.getContext().showMessage("导出失败");
            return 0L;
        }
        try {
            File file = new File(buildExternalDirectoryPath,
                    CommonUtil.buildUniqueFileName(new File(buildExternalDirectoryPath),
                            !TextUtils.isEmpty(byId.getTitle()) ? byId.getTitle()
                                    : WorkoutTitleUtil.buildWorkoutDefaultTitle(context, byId),
                            DeepLinkPathConstants.FILE_TYPE_GPX));
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            GpxTrackWriter gpxTrackWriter = new GpxTrackWriter(context);
            gpxTrackWriter.prepare(fileOutputStream);
            gpxTrackWriter.writeHeader(byId);
            gpxTrackWriter.writeBeginTrack(byId);
            gpxTrackWriter.writeOpenSegment();
            for (int i = 0; i < queryTrackPoint.size(); i++) {
                gpxTrackWriter.writePoint(queryTrackPoint.get(i));
            }
            gpxTrackWriter.writeCloseSegment();
            gpxTrackWriter.writeEndTrack();
            gpxTrackWriter.writeFooter();
            gpxTrackWriter.close();
            long importFile = file.exists() ? importFile(file, true) : 0L;
            if (importFile > 0) {
                if (isMyRouteBook) {
                    App.getContext().showMessage("导出成功，已保存到本地路书");
                } else {
                    App.getContext().showMessage("可以在【路书】-【我的】-【已下载】中找到");
                }
                SharedManager.getInstance().setCreateRouteMineIsNeedRefresh(1);
                SharedManager.getInstance().setCreateRouteBookDownloadIsNeedRefresh(1);
                App.getContext().sendBroadcast(new Intent(RouteBook.ACTION_WORKOUT_CREATE_LUSHU));
            } else {
                App.getContext().showMessage("导出失败");
            }
            return importFile;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            App.getContext().showMessage("导出失败");
            return 0L;
        }
    }

    public static long importFile(final File file) {
        return importFile(file, false);
    }

    public static long importFile(final File file, boolean keepFile) {
        try {
            long valueOf = SaxGpxImporter.importGPXFile(file);
            List<RouteBookPoint> byLushuId = RouteBookPoint.getByLushuId(valueOf);
            if (byLushuId.size() <= 2) {
                RouteBook byId = RouteBook.getById(valueOf);
                if (byId != null) {
                    byId.delete();
                }
                valueOf = 0L;
            } else {
                ArrayList<Waypoint> arrayList = new ArrayList<>();
                Waypoint waypoint = new Waypoint();
                waypoint.setLushuId(valueOf);
                waypoint.setLatLng(byLushuId.get(0).getLatLng());
                arrayList.add(waypoint);
                Waypoint waypoint2 = new Waypoint();
                waypoint2.setLushuId(valueOf);
                waypoint2.setLatLng(byLushuId.get(byLushuId.size() - 1).getLatLng());
                arrayList.add(waypoint2);
                Waypoint.savePoints(arrayList);
            }
            return valueOf;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    public static long parseGpxFile(String body, RouteBook routeBook) {
        String str = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_CACHE)
                + (routeBook.getUuid() + DeepLinkPathConstants.FILE_SUFFIX_GPX);
        File file = new File(str);
        int i = 0;
        FileWriter fileWriter;
        try {
            try {
                StringReader stringReader = new StringReader(body);
                FileWriter fileWriter2 = new FileWriter(str);
                try {
                    char[] cArr = new char[1024];
                    while (true) {
                        int read = stringReader.read(cArr);
                        if (read == -1) {
                            break;
                        }
                        fileWriter2.write(cArr, 0, read);
                    }
                    fileWriter2.flush();
                    // TODO feng 此注释处暂时不可以打开，打开后会因无法执行，导致导航在此步骤卡住
                    // SaxGpxImporter.parseGpxFileWithLushu(file, lushu);
                    try {
                        fileWriter2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e2) {
                    fileWriter = fileWriter2;
                    e2.printStackTrace();
                    try {
                        fileWriter.close();
                    } catch (IOException e3) {
                        e3.printStackTrace();
                    }
                } catch (Throwable th) {
                    th = th;
                    fileWriter = fileWriter2;
                    try {
                        fileWriter.close();
                    } catch (IOException e4) {
                        e4.printStackTrace();
                    }
                    if (file.exists()) {
                        file.delete();
                    }
                    throw th;
                }
            } catch (Throwable th2) {
            }
        } catch (Exception e5) {
        }
        i++;
        return i;
    }

    public static long parseDirection(String str, List<BiciLatlng> list, RouteBook routeBook, int i)
            throws JSONException {
        JSONObject jSONObject = new JSONObject(str);
        if (i == TYPE_GOOGLE) {
            if (jSONObject.has("routes_baidu")) {
                return parseBDDirection(jSONObject, str, list, routeBook);
            }
            return parseGoogleDirection(jSONObject, str, list, routeBook);
        } else if (i == TYPE_BAIDU) {
            return parseBDDirection(jSONObject, str, list, routeBook);
        } else {
            try {
                return parseGoogleDirection(jSONObject, str, list, routeBook);
            } catch (Exception e) {
                Log.e("lushu", "pares direction error", e);
                return 0L;
            }
        }
    }

    // 服务器返回解析
    public static long parseDirectionNew(String str, List<BiciLatlng> list, RouteBook routeBook, int i)
            throws JSONException {
        JSONObject jSONObject = new JSONObject(str);
        if (i == TYPE_GOOGLE) {
            if (jSONObject.has("routes_baidu")) {
                return parseBDDirection(jSONObject, str, list, routeBook);
            }
            return parseGoogleDirection(jSONObject, str, list, routeBook);
        } else if (i == TYPE_BAIDU || i == TYPE_IMPORT) {
            return parseBDDirectionNew(jSONObject, list, routeBook);
        } else {
            try {
                return parseGoogleDirection(jSONObject, str, list, routeBook);
            } catch (Exception e) {
                Log.e("lushu", "pares direction error", e);
                return 0L;
            }
        }
    }

    private static long parseGoogleDirection(JSONObject jsonObject, String body, List<BiciLatlng> latlngs,
            RouteBook routeBook) throws JSONException {
        String string = jsonObject.getString("status");
        if ("OK".equals(string)) {
            JSONArray jSONArray = jsonObject.getJSONArray("routes");
            if (jSONArray.length() < 1) {
                return 0L;
            }
            JSONObject jSONObject = jSONArray.getJSONObject(0);
            if (routeBook == null) {
                routeBook = RouteBook.parseLushuByGoogle(jSONObject);
            } else {
                RouteBook.parseLushuByGoogle(jSONObject, routeBook);
            }
            if (latlngs != null && !latlngs.isEmpty()) {
                String address = latlngs.get(0).getAddress();
                String address2 = latlngs.get(latlngs.size() - 1).getAddress();
                if (!TextUtils.isEmpty(address)) {
                    routeBook.setStartAddress(address);
                }
                if (!TextUtils.isEmpty(address2)) {
                    routeBook.setEndAddress(address2);
                }
            }
            routeBook.setSourceType(TYPE_GOOGLE);
            routeBook.save();
            parseWayPoints(latlngs, routeBook);
            if (jSONObject.has("overview_polyline")) {
                saveDirectionFile(body, routeBook.getUuid());
            } else {
                List<RouteBookPoint> byLushuId = RouteBookPoint.getByLushuId(routeBook.getId());
                if (byLushuId != null && !byLushuId.isEmpty()) {
                    ArrayList<LatLng> arrayList = new ArrayList<>(byLushuId.size());
                    for (RouteBookPoint lushuPoint : byLushuId) {
                        arrayList.add(lushuPoint.getLatLng());
                    }
                    Route analyse = new PolyAnalyzer().analyse(arrayList);
                    com.alibaba.fastjson.JSONObject jSONObject2 = new com.alibaba.fastjson.JSONObject();
                    jSONObject2.put("routes", JSON.toJSONString(new Route[] { analyse }));
                    String jSONString = jSONObject2.toJSONString();
                    String str = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION)
                            + (routeBook.getUuid() + ".bb");
                    Log.d(TAG, "saveDirectionFile, filePath = " + str + ", md5 = "
                            + AppFileUtils.buildGZIPFile(jSONString, str));
                }
            }
            return routeBook.getId();
        }
        String str2 = "NOT_FOUND".equals(string) ? "发生错误 : 无法解析位置" : "发生错误 : ";
        if ("ZERO_RESULTS".equals(string)) {
            str2 = str2 + "没有找到路线";
        }
        if ("MAX_WAYPOINTS_EXCEEDED".equals(string)) {
            str2 = str2 + "途经点超过限制";
        }
        if ("INVALID_REQUEST".equals(string)) {
            str2 = str2 + "无效的请求";
        }
        if ("OVER_QUERY_LIMIT".equals(string)) {
            str2 = str2 + "超出限制";
        }
        if ("REQUEST_DENIED".equals(string)) {
            str2 = str2 + "请求被拒绝";
        }
        if ("UNKNOWN_ERROR".equals(string)) {
            str2 = str2 + "未知错误";
        }
        App.getContext().showMessage(str2);
        return 0L;
    }

    private static void parseWayPoints(List<BiciLatlng> latlngs, RouteBook routeBook) {
        ArrayList<Waypoint> arrayList = new ArrayList<>();
        int i = 0;
        if (latlngs != null && !latlngs.isEmpty()) {
            Waypoint.deleteByRouteBookId(routeBook.getId());
            while (i < latlngs.size()) {
                BiciLatlng biciLatlng = latlngs.get(i);
                Waypoint waypoint = new Waypoint();
                waypoint.setLushuId(routeBook.getId());
                waypoint.setLatitude(biciLatlng.getLatitude());
                waypoint.setLongitude(biciLatlng.getLongitude());
                waypoint.setTitle(biciLatlng.getName());
                waypoint.setContent(biciLatlng.getContent());
                waypoint.setImage(biciLatlng.getImage());
                waypoint.setType(biciLatlng.isCheckPoint() ? 1 : 0);
                arrayList.add(waypoint);
                i++;
            }
        } else {
            JSONArray waypointJsonArray = routeBook.getWaypointJsonArray();
            if (waypointJsonArray != null && waypointJsonArray.length() > 0) {
                Waypoint.deleteByRouteBookId(routeBook.getId());
                while (i < waypointJsonArray.length()) {
                    try {
                        Waypoint waypoint2 = new Waypoint();
                        JSONObject jSONObject = waypointJsonArray.getJSONObject(i);
                        waypoint2.setLushuId(routeBook.getId());
                        waypoint2.setLatitude(JsonUtil.getDoubleValue("latitude", jSONObject));
                        waypoint2.setLongitude(JsonUtil.getDoubleValue("longitude", jSONObject));
                        waypoint2.setTitle(JsonUtil.getStringValue("title", jSONObject));
                        waypoint2.setContent(JsonUtil.getStringValue("content", jSONObject));
                        waypoint2.setImage(JsonUtil.getStringValue(SocializeProtocolConstants.IMAGE, jSONObject));
                        waypoint2.setType(JsonUtil.getIntegerValue("type", jSONObject));
                        arrayList.add(waypoint2);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    i++;
                }
            } else {
                List<RouteBookPoint> byLushuId = RouteBookPoint.getByLushuId(routeBook.getId());
                if (!byLushuId.isEmpty()) {
                    Waypoint.deleteByRouteBookId(routeBook.getId());
                    Waypoint waypoint3 = new Waypoint();
                    waypoint3.setLatLng(byLushuId.get(0).getLatLng());
                    arrayList.add(waypoint3);
                    Waypoint waypoint4 = new Waypoint();
                    waypoint4.setLatLng(byLushuId.get(byLushuId.size() - 1).getLatLng());
                    arrayList.add(waypoint4);
                }
            }
        }
        Waypoint.savePoints(arrayList);
    }

    public static long parseBDDirectionNew(JSONObject jsonObject, List<BiciLatlng> latlngs, RouteBook routeBook)
            throws JSONException {
        if (routeBook == null) {
            routeBook = RouteBook.parseLushuByServer(jsonObject, false);
        }
        RouteBook.parseLushu(jsonObject, routeBook);
        if (jsonObject.has("info")) {
            JSONObject infoJSONObject = jsonObject.getJSONObject("info");
            if (infoJSONObject.has("copyright")) {
                JSONObject copyrightJSONObject = infoJSONObject.getJSONObject("copyright");
                if (copyrightJSONObject.has("text")) {
                    routeBook.setCopyrights(JsonUtil.getStringValue("text", copyrightJSONObject));
                }
            }
        }

        if (latlngs != null && !latlngs.isEmpty()) {
            routeBook.setStartAddress(latlngs.get(0).getAddress());
            routeBook.setEndAddress(latlngs.get(latlngs.size() - 1).getAddress());
        }
        parseWayPoints(latlngs, routeBook);
        routeBook.setSourceType(TYPE_BAIDU);
        return routeBook.save_();
    }

    private static long parseBDDirection(JSONObject jsonObject, String body, List<BiciLatlng> latlngs,
            RouteBook routeBook) throws JSONException {
        JSONArray jSONArray = null;
        if (jsonObject.has("routes")) {
            jSONArray = jsonObject.getJSONArray("routes");
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("status", 0);
            JSONObject jSONObject2 = new JSONObject();
            jSONObject2.put("copyright", BaiduNavConvert.getCopyright());
            jSONObject.put("info", jSONObject2);
            if (!jsonObject.has("info")) {
                jsonObject.put("info", jSONObject2);
            }
        } else {
            if (jsonObject.getInt("status") == 0) {
                jSONArray = jsonObject.getJSONObject("result").getJSONArray("routes");
            }
        }
        if (jSONArray == null || jSONArray.length() < 1) {
            return 0L;
        }
        JSONObject jSONObject4 = jSONArray.getJSONObject(0);
        if (routeBook == null) {
            routeBook = new RouteBook();
            routeBook.setUuid(UUID.randomUUID().toString());
            routeBook.setUserId(SharedManager.getInstance().getUserId());
            routeBook.setServerType(TYPE_SOURCE_CREATE);
            routeBook.setCreateTime(System.currentTimeMillis());
            routeBook.setSport(Workout.TYPE_CYCLING);
            // routeBook.setTitle(LushuTitleUtil.buildLushuDefaultTitle(App.getContext(), routeBook));
        }
        RouteBook.parseLushuByBaidu(jSONObject4, routeBook);
        if (jsonObject.has("info")) {
            JSONObject infoJSONObject = jsonObject.getJSONObject("info");
            if (infoJSONObject.has("copyright")) {
                JSONObject copyrightJSONObject = infoJSONObject.getJSONObject("copyright");
                if (copyrightJSONObject.has("text")) {
                    routeBook.setCopyrights(JsonUtil.getStringValue("text", copyrightJSONObject));
                }
            }
        }

        if (latlngs != null && !latlngs.isEmpty()) {
            routeBook.setStartAddress(latlngs.get(0).getAddress());
            routeBook.setEndAddress(latlngs.get(latlngs.size() - 1).getAddress());
        }
        parseWayPoints(latlngs, routeBook);
        //if (!TextUtils.isEmpty(body)) {
        //    saveDirectionToFile(body, routeBook.getUuid());
        //}
        routeBook.setSourceType(TYPE_BAIDU);
        return routeBook.save_();
    }

    private static String saveDirectionFile(String strDirection, String uuid) {
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION);
        String filePath = buildExternalDirectoryPath + (uuid + ".bb");
        File file = new File(buildExternalDirectoryPath, uuid + ".bd");
        if (file.exists()) {
            file.delete();
        }
        String buildGZIPFile = AppFileUtils.buildGZIPFile(strDirection, filePath);
        Log.d(TAG, "saveDirectionFile, filePath = " + filePath + ", md5 = " + buildGZIPFile);
        return buildGZIPFile;
    }

    public static String saveDirectionFile(String strDirection, long serverId, String type) {
        boolean result = false;

        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION);
        String filePath = buildExternalDirectoryPath + (serverId + LUSHU_BAIDU_FILE_SUFFIX);
        if ("gpx".equals(type)) {
            filePath = buildExternalDirectoryPath + (serverId + LUSHU_GPX_FILE_SUFFIX);
        }
        result = saveDirectionToFile(strDirection, filePath);
        if (result) {
            return filePath;
        }
        return null;
    }

    public static boolean saveDirectionToFile(String strDirection, String filePath) {
        boolean result = false;
        result = AppFileUtils.writeFileWithCallBack(strDirection, filePath);
        return result;
    }

    public static void deleteRouteBookBefore(long lushuId) {
        for (int i = 0; i < lushuId; i++) {
            deleteRouteBook(RouteBook.getById(i));
        }
    }

    public static boolean deleteRouteBook(RouteBook routeBook) {
        int sourceType = 0;
        boolean z = false;
        if (routeBook == null) {
            return false;
        }
        File file = null;
        try {
            sourceType = routeBook.getSourceType();
            if (sourceType == 0) {
                file = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION)
                        + (routeBook.getUuid() + LUSHU_BAIDU_FILE_SUFFIX));
            } else {
                if (2 == sourceType) {
                    String fileName = routeBook.getFileName();
                    if (!TextUtils.isEmpty(fileName)) {
                        file = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_IMPORT) + fileName);
                    }
                } else if (sourceType == RouteBook.TYPE_BAIDU) {
                    File folder = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION_UPLOAD));
                    // 删除文件夹下所有的文件内容,这个是临时的文件
                    FileUtils.deleteAllInDir(folder);
                }
            }
            if (null != file) {
                file.delete();
            }
            return true;
        } finally {
            deleteRouteBookDB(routeBook);
        }
    }

    public static boolean deleteRouteBookDB(RouteBook routeBook) {
        if (routeBook == null) {
            return false;
        }
        LitePal.delete(RouteBook.class, routeBook.getId());
        RouteBookPoint.deleteByRouteBookId(routeBook.getId());
        Waypoint.deleteByRouteBookId(routeBook.getId());
        return true;
    }

    public static void deleteRouteBookFiles(List<String> stringList) {
        executorService.execute(() -> {
            File folder = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION));
            if (folder.exists()) {
                for (String item : stringList) {
                    File file = new File(folder, item);
                    FileUtils.delete(file);
                }
            }
        });

    }

    public static void showRouteBookCreateDialog(final Context context, @NonNull Fragment fragment,
            final int requestCode, final ActivityResultLauncher<String> activityResultLauncher) {
        if (context == null) {
            return;
        }
        final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.width = (int) (ScreenUtils.getScreenWidth() * 0.95);
        attributes.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        attributes.gravity = Gravity.CENTER;
        View inflate = LayoutInflater.from(context).inflate(R.layout.dialog_lushu_make_chose, null);
        window.setContentView(inflate);
        window.setAttributes(attributes);
        View normalStyle = inflate.findViewById(R.id.normalStyle);
        View importStyle = inflate.findViewById(R.id.importStyle);
        View cancel = inflate.findViewById(R.id.cancel);

        normalStyle.setOnClickListener(view -> {
            if (!App.getContext().isUserSignin()) {
                App.getContext().userSignin();
                return;
            }
            Intent intent = new Intent(context, BaiduRouteBookCreateActivity.class);
            fragment.startActivityForResult(intent, requestCode);
            alertDialog.dismiss();
        });
        importStyle.setOnClickListener(view -> {
            if (null != activityResultLauncher) {
                activityResultLauncher.launch("application/*");
            }
            alertDialog.dismiss();
        });
        cancel.setOnClickListener(view -> {
            alertDialog.dismiss();
        });
    }

    public static List<RouteBookPoint> parseAltitudeData(JSONArray jsonArray) throws JSONException {
        if (jsonArray == null || jsonArray.length() <= 0) {
            return null;
        }
        ArrayList<RouteBookPoint> arrayList = new ArrayList<>(jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jSONObject = (JSONObject) jsonArray.get(i);
            double doubleValue = JsonUtil.getDoubleValue("elevation", jSONObject);
            JSONObject objectValue = JsonUtil.getObjectValue("location", jSONObject);
            double doubleValue2 = JsonUtil.getDoubleValue("lat", objectValue);
            double doubleValue3 = JsonUtil.getDoubleValue("lng", objectValue);
            RouteBookPoint lushuPoint = new RouteBookPoint();
            lushuPoint.setAltitude(doubleValue);
            lushuPoint.setLatitude(doubleValue2);
            lushuPoint.setLongitude(doubleValue3);
            arrayList.add(lushuPoint);
        }
        return arrayList;
    }

    public static void showDialogForDownloadedRouteBook(Context context) {
        if (!SharedManager.getInstance().getBoolean(KEY_DOWNLOAD_LUSHU_FIRST, true) || isDestroyed(context)) {
            return;
        }
        final Dialog dialog = new Dialog(context, R.style.AppTheme_NoBackground_AlertDialog);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(R.layout.dialog_routebook_location);
        ((TextView) dialog.findViewById(R.id.dialog_content))
                .setText(Html.fromHtml(context.getString(R.string.message_lushu_downlaoded)));
        (dialog.findViewById(R.id.tvGoTo)).setOnClickListener(view -> dialog.dismiss());
        dialog.show();
        SharedManager.getInstance().setValue(KEY_DOWNLOAD_LUSHU_FIRST, false);
    }

    public static void showDialogForCreatedLushu(Context context) {
        if (!SharedManager.getInstance().getBoolean(KEY_CREATE_LUSHU_FIRST, true) || isDestroyed(context)) {
            return;
        }
        final Dialog dialog = new Dialog(context, R.style.AppTheme_NoBackground_AlertDialog);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(R.layout.dialog_routebook_location);
        ((TextView) dialog.findViewById(R.id.dialog_content))
                .setText(Html.fromHtml(context.getString(R.string.message_lushu_created)));
        (dialog.findViewById(R.id.tvGoTo)).setOnClickListener(view -> dialog.dismiss());
        dialog.show();
        SharedManager.getInstance().setValue(KEY_CREATE_LUSHU_FIRST, false);
    }

    public static void showDialogForCollectedRouteBook(Context context) {
        if (!SharedManager.getInstance().getBoolean(KEY_COLLECTION_LUSHU_FIRST, true) || isDestroyed(context)) {
            return;
        }
        final Dialog dialog = new Dialog(context, R.style.AppTheme_NoBackground_AlertDialog);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(R.layout.dialog_routebook_location);
        ((TextView) dialog.findViewById(R.id.dialog_content))
                .setText(Html.fromHtml(context.getString(R.string.message_lushu_collected)));
        (dialog.findViewById(R.id.tvGoTo)).setOnClickListener(view -> dialog.dismiss());
        dialog.show();
        SharedManager.getInstance().setValue(KEY_COLLECTION_LUSHU_FIRST, false);
    }

    public static void uploadRouteBookUseBehavior(long lushuId, int action) {
        if (App.getContext().isUserSignin()) {
            MyHttpClient.uploadLushuUseBehavior(lushuId, action).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                }
            });
        }
    }

    private static boolean isDestroyed(Context context) {
        if ((context instanceof Activity activity)) {
            return activity.isDestroyed() || activity.isFinishing();
        }
        return true;
    }
}
